/**
 * 身份验证相关工具函数
 */

const { handleTokenExpired } = require('./request.js');
const { checkLoginStatus } = require('./api.js');

/**
 * 页面级token检查中间件
 * 在页面的onLoad或onShow中调用，确保用户已登录
 * @param {Object} pageInstance 页面实例 (this)
 * @param {boolean} showToast 是否显示提示信息
 * @returns {boolean} 是否已登录
 */
const requireAuth = (pageInstance, showToast = true) => {
  try {
    if (!checkLoginStatus()) {
      if (showToast) {
        wx.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 1500
        });
      }
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login'
        });
      }, showToast ? 1500 : 0);
      
      return false;
    }
    return true;
  } catch (error) {

    return false;
  }
};

/**
 * 检查token是否即将过期（提前1天提醒）
 * @returns {Object} 检查结果
 */
const checkTokenExpiringSoon = () => {
  try {
    const userInfo = wx.getStorageSync('userInfo');
    
    if (!userInfo || !userInfo.loginTime) {
      return {
        isExpiringSoon: false,
        isExpired: true,
        remainingDays: 0
      };
    }
    
    const currentTime = new Date().getTime();
    const loginTime = userInfo.loginTime;
    const tokenExpireDays = 7; // token过期天数
    const warningDays = 1; // 提前警告天数
    
    const expireTime = tokenExpireDays * 24 * 60 * 60 * 1000;
    const warningTime = (tokenExpireDays - warningDays) * 24 * 60 * 60 * 1000;
    
    const elapsedTime = currentTime - loginTime;
    const remainingTime = expireTime - elapsedTime;
    const remainingDays = Math.ceil(remainingTime / (24 * 60 * 60 * 1000));
    
    return {
      isExpiringSoon: elapsedTime > warningTime && elapsedTime < expireTime,
      isExpired: elapsedTime >= expireTime,
      remainingDays: Math.max(0, remainingDays)
    };
  } catch (error) {

    return {
      isExpiringSoon: false,
      isExpired: false,
      remainingDays: 0
    };
  }
};

/**
 * 显示token即将过期的提醒
 * @param {number} remainingDays 剩余天数
 */
const showTokenExpiringWarning = (remainingDays) => {
  wx.showModal({
    title: '登录即将过期',
    content: `您的登录状态将在${remainingDays}天后过期，建议重新登录以确保正常使用。`,
    confirmText: '重新登录',
    cancelText: '稍后再说',
    success: (res) => {
      if (res.confirm) {
        wx.reLaunch({
          url: '/pages/login/login'
        });
      }
    }
  });
};

/**
 * 自动检查并处理token状态
 * 建议在页面的onShow中调用
 * @param {boolean} showWarning 是否显示即将过期警告
 */
const autoCheckTokenStatus = (showWarning = true) => {
  try {
    const status = checkTokenExpiringSoon();
    
    if (status.isExpired) {
      handleTokenExpired('登录已过期，请重新登录');
      return false;
    }
    
    if (status.isExpiringSoon && showWarning) {
      showTokenExpiringWarning(status.remainingDays);
    }
    
    return true;
  } catch (error) {

    return false;
  }
};

/**
 * 为页面添加身份验证行为
 * @param {Object} pageOptions 页面配置对象
 * @param {Object} options 认证选项
 * @returns {Object} 增强后的页面配置
 */
const withAuth = (pageOptions, options = {}) => {
  const {
    requireLogin = true,
    showWarning = true,
    checkOnLoad = true,
    checkOnShow = true
  } = options;
  
  const originalOnLoad = pageOptions.onLoad || function() {};
  const originalOnShow = pageOptions.onShow || function() {};
  
  return {
    ...pageOptions,
    onLoad(query) {
      if (requireLogin && checkOnLoad) {
        if (!requireAuth(this, true)) {
          return; // 如果未登录，直接返回
        }
      }
      
      if (checkOnLoad) {
        autoCheckTokenStatus(showWarning);
      }
      
      originalOnLoad.call(this, query);
    },
    
    onShow() {
      if (requireLogin && checkOnShow) {
        if (!requireAuth(this, false)) {
          return; // 如果未登录，直接返回
        }
      }
      
      if (checkOnShow) {
        autoCheckTokenStatus(showWarning);
      }
      
      originalOnShow.call(this);
    }
  };
};

module.exports = {
  requireAuth,
  checkTokenExpiringSoon,
  showTokenExpiringWarning,
  autoCheckTokenStatus,
  withAuth
};